package com.l.web.common.freemark;

import com.l.web.master.system.dictionary.Dictionary;
import com.l.web.master.system.dictionary.DictionaryService;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.l.qiao.Cluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/4.
 * Freemarker中直接获取字典文本
 */
@Component
public class FreemarkerDictionary implements TemplateMethodModelEx {

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    public Object exec(List list) throws TemplateModelException {
        if (list.size() != 2) {
            throw new TemplateModelException("参数错误：（字典号，值）");
        }

        int id = Integer.parseInt(list.get(0).toString());
        Object value = list.get(1);

        if (value == null) {
            return null;
        }

        Cluster dict = dictionaryService.dictionary(id);
        Map<String, Object> keys = dict.getMap(Dictionary.KEY);
        return keys == null ? null : keys.get(value.toString());
    }
}
